import Singleton from "../Base/Singleton"
import { ApiMsgEnum, IApiPlayerJoinReq } from "../Common"
import { Connection } from "../Core"
import { Player } from "./Player"
import { RoomManager } from "./RoomManager"

export class PlayerManager extends Singleton {
    static get Instance() {
        return super.GetInstance<PlayerManager>()
    }

    nextPlayerId = 1

    players: Set<Player> = new Set()
    idMapPlayer: Map<number, Player> = new Map()

    // createPlayer({ nickname, connection }: any) {
    createPlayer({ nickname, connection }: IApiPlayerJoinReq & { connection: Connection }) {
        const player = new Player({
            id: this.nextPlayerId++,
            nickname,
            connection
        })
        this.players.add(player)
        this.idMapPlayer.set(player.id, player)
        return player
    }

    removePlayer(pid: number) {
        const player = this.idMapPlayer.get(pid)
        if (player) {
            const rid = player.rid
            if (rid) {
                RoomManager.Instance.leaveRoom(rid, player.id)
                RoomManager.Instance.syncRoom(rid)
                RoomManager.Instance.syncRooms()
            }
            this.players.delete(player)
            this.idMapPlayer.delete(pid)
        }
    }

    // 同步玩家列表给所有玩家，主要是为了更新玩家列表
    syncPlayers() {
        const playerList = this.getPlayersView()
        for (const player of this.players) {
            player.connection.sendMsg(ApiMsgEnum.MsgPlayerList, {
                list: playerList
            })
        }
    }

    getPlayersView(players: Set<Player> = this.players) {
        return Array.from(players).map(player => this.getPlayerView(player))
        // return [...players].map(player => this.getPlayerView(player))
    }

    // 有些字段不需要暴露给客户端，比如 connection
    getPlayerView({ id, nickname, rid }: Player) {
        return {
            id,
            nickname,
            rid
        }
    }
}